package handler

import (
	"context"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/micro/go-micro/util/log"
	"ihome/models"
	"ihome/utils"
	"time"

	getIndex "ihome/proto/getIndex"
)

type GetIndex struct{}

// 获取首页轮播
func (e *GetIndex) SrvGetIndex(ctx context.Context, req *getIndex.Request, rsp *getIndex.Response) error {
	logs.Info("获取首页轮播 GetIndex /api/v1.0/houses/index")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	homePageValue := bm.Get("home_page_data")

	if homePageValue != nil {
		logs.Info("获取到轮播图缓存")
		rsp.Mix = homePageValue.([]byte)
		return nil
	}

	var houses []models.House
	var data []interface{}
	o := orm.NewOrm()
	if _, err := o.QueryTable("house").Limit(models.HOME_PAGE_MAX_HOUSES).All(&houses); err == nil {
		for _, house := range houses {
			o.LoadRelated(&house, "Area")
			o.LoadRelated(&house, "User")
			o.LoadRelated(&house, "Images")
			o.LoadRelated(&house, "Facilities")
			data = append(data, house.To_house_info())
		}
	}

	housePageValue, _ := json.Marshal(data)
	bm.Put("home_page_data", housePageValue, 3600*time.Second)

	rsp.Mix = housePageValue

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetIndex) Stream(ctx context.Context, req *getIndex.StreamingRequest, stream getIndex.GetIndex_StreamStream) error {
	log.Logf("Received GetIndex.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&getIndex.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetIndex) PingPong(ctx context.Context, stream getIndex.GetIndex_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&getIndex.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
